package com.ts.oss.service.impl;

import com.aliyun.vod.upload.impl.UploadImageImpl;
import com.aliyun.vod.upload.impl.UploadVideoImpl;
import com.aliyun.vod.upload.req.UploadImageRequest;
import com.aliyun.vod.upload.req.UploadStreamRequest;
import com.aliyun.vod.upload.resp.UploadImageResponse;
import com.aliyun.vod.upload.resp.UploadStreamResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthRequest;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthResponse;
import com.ts.oss.service.VodService;
import com.ts.oss.util.ConstantPropertiesUtils;
import com.ts.oss.util.ImageRotation;
import com.ts.oss.util.InitVodClient;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.Java2DFrameConverter;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;

@Service
public class VodServiceImpl implements VodService {
    @Override
    public String uploadVideo(MultipartFile multipartFile) {


        //获取文件名
        String originalFilename = multipartFile.getOriginalFilename();
        UploadStreamResponse response=null;
        String title = originalFilename.substring(0, originalFilename.lastIndexOf("."));
        try {
            InputStream inputStream = multipartFile.getInputStream();
            UploadStreamRequest request = new UploadStreamRequest(ConstantPropertiesUtils.KEY_ID, ConstantPropertiesUtils.KEY_SECRET, title, originalFilename, inputStream);
            UploadVideoImpl uploader = new UploadVideoImpl();
            response = uploader.uploadStream(request);
//            System.out.println("======================");
//            System.out.println(request.getCoverURL());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return response.getVideoId();
    }

    @Override
    public String[] uploadVideoAndImage(MultipartFile multipartFile) {
        String[] strings = new String[3];



        try {
            InputStream inputStream = multipartFile.getInputStream();



            //
            final int fifthFrame= 10;

            FFmpegFrameGrabber grabber;

            grabber = new FFmpegFrameGrabber(inputStream);

            grabber.start();
            // 视频总帧数
            int videoLength = grabber.getLengthInFrames();

            Frame frame = null;
            int i = 0;
            while (i < videoLength) {
                // 过滤前5帧,因为前5帧可能是全黑的
                frame = grabber.grabFrame();
                if ((i > fifthFrame) && (frame.image != null)) {
                    break;
                }
                i++;
            }

            Java2DFrameConverter converter = new Java2DFrameConverter();
            // 绘制图片
            BufferedImage bi = converter.getBufferedImage(frame);
            BufferedImage rotatedImage = ImageRotation.rotateImage(bi, 90);


            grabber.stop();
            grabber.close();

            //将图片转换成输入流
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            ImageIO.write(rotatedImage, "png", os);
            InputStream input = new ByteArrayInputStream(os.toByteArray());

            //绘制完图片后 直接以流的方式将封面图片上传到阿里云
            String imageType = "default";
            UploadImageRequest Imagerequest = new UploadImageRequest("LTAI5t6a4Bwa6d21Pd2NRAqo", "QLPSNZCYpe6EI70adnq8s9GRgvcYqo", imageType);
            Imagerequest.setInputStream(input);
            UploadImageImpl uploadImage = new UploadImageImpl();
            UploadImageResponse Imageresponse = uploadImage.upload(Imagerequest);
            if(Imageresponse.isSuccess())
            {
                String imageURL = Imageresponse.getImageURL();
                strings[0]=imageURL;
                String imageId = Imageresponse.getImageId();
                strings[1]=imageId;
                //上传结束后获得图片的url 将图片的Url作为视频的封面图片

                //获取文件名
                String originalFilename = multipartFile.getOriginalFilename();
                UploadStreamResponse response=null;
                //上传的视频的标题
                String title = originalFilename.substring(0, originalFilename.lastIndexOf("."));
                UploadStreamRequest request = new UploadStreamRequest(ConstantPropertiesUtils.KEY_ID, ConstantPropertiesUtils.KEY_SECRET, title, originalFilename, multipartFile.getInputStream());
                request.setCoverURL(imageURL);
                UploadVideoImpl uploader = new UploadVideoImpl();
                response = uploader.uploadStream(request);
                String videoId = response.getVideoId();
                System.out.println(videoId);
                strings[2]=videoId;

            }






        } catch (IOException e) {
            e.printStackTrace();
        }


        return strings;
    }

    @Override
    public String getPlayIdAndAuth(String id) {

        try {
            DefaultAcsClient defaultAcsClient = InitVodClient.initVodClient(ConstantPropertiesUtils.KEY_ID, ConstantPropertiesUtils.KEY_SECRET);
            GetVideoPlayAuthRequest request = new GetVideoPlayAuthRequest();
            GetVideoPlayAuthResponse response;
            request.setVideoId(id);
            response=defaultAcsClient.getAcsResponse(request);
            String playAuth = response.getPlayAuth();

            return playAuth;
        } catch (ClientException e) {
            e.printStackTrace();
            return null;

        }

    }
}
